<template>
    <div>
        <div class="handel-header">
            <flexbox justify="space-between" @click.stop>
              <span style="font-size: 14px;font-weight: 600;padding-left: 10px">{{"第" + (index+1) + "项："}}{{quotationData.itemOption}}</span>
              <el-popover
                v-model="showPopover"
                placement="bottom"
                width="700"
                style="padding: 0 !important;"
                trigger="click">
                <crm-relative
                    v-if="showSelectView"
                    ref="crmrelative"
                    :radio="false"
                    :show="showPopover"
                    :selected-data="selectedData"
                    :action="{type: 'condition',data: {item: quotationData}}"
                    crm-type="product"
                    @close="showPopover=false"
                    @changeCheckout="selectInfos"/>
                    <el-button 
                      slot="reference" 
                      @click="showSelectView=true"
                      style="margin: 0"
                      type="primary" >关联产品</el-button>
                </el-popover>
            </flexbox>
          </div>
          <el-table
              :data="productList"
              style="width: 100%;">
              <el-table-column
                  label="序号">
                  <template slot-scope="scope">
                    <span>{{scope.$index + 1}}</span>
                  </template>
              </el-table-column>
              <el-table-column
                  prop="productName"
                  label="产品名称"/>
              <el-table-column
                  prop="productModel"
                  label="型号"/>
              <el-table-column label="单价">
                  <template slot-scope="scope">
                    <el-input
                        v-model="scope.row.productPrice"
                        type="number"
                        @blur="changeData(scope,'productPrice')"
                        @mousewheel.native.prevent
                        placeholder="请输入"/>
                  </template>
              </el-table-column>
              <el-table-column label="数量">
                  <template slot-scope="scope">
                  <el-input
                      v-model="scope.row.productNumber"
                      @blur="changeData(scope,'productNumber')"
                      @mousewheel.native.prevent
                      type="number"
                      placeholder="请输入"/>
                  </template>
              </el-table-column>
              <el-table-column
                  prop="totalPrice"
                  label="总价">
                  <!-- <template slot-scope="scope">
                    <span>{{ calculationTotalPrice(scope) }}</span>
                  </template> -->
              </el-table-column>
              <el-table-column label="备注">
                  <template slot-scope="scope">
                  <el-input
                      v-model="scope.row.remark"
                      type="textarea"
                      rows="1"
                      :autosize="{ minRows: 1, maxRows: 2 }"
                      placeholder="请输入备注"/>
                  </template>
              </el-table-column>
              <el-table-column label="操作">
                  <template slot-scope="scope">
                    <el-button type="danger" plain @click="removeItem(scope.$index)">删除</el-button>
                  </template>
              </el-table-column>
          </el-table>
          <flexbox class="handle-footer" align="center" justify="flex-end">
              <!-- <flexbox style="width: 50%">
                  <div class="discount-title">增值税率（%）：</div>
                  <el-select
                      v-model="quotationData.rate"
                      filterable
                      :disabled="!productList.length"
                      @change="changeRate"
                      placeholder="请选择">
                      <el-option
                          v-for="optionItem in optionsList.vatRate"
                          :key="optionItem.id"
                          :label="optionItem.name"
                          :value="optionItem.id"/>
                  </el-select>
              </flexbox> -->
              <div class="total-info">
                  <span>小计：<label style="font-weight: bold">{{quotationData.subtotal || quotationData.subtotal == 0 ? quotationData.subtotal : "--"}}</label>&nbsp;元</span>    
              </div>
          </flexbox>
    </div>
</template>
<script type="text/javascript">
import objMixin from './objMixin'
import CrmRelative from '@/components/CreateCom/CrmRelative'
import { numberAdd, numberSub,numberMul,numberDiv } from '@/utils'
export default {
  name: 'CrmRelativeQuotation', // 关联产品
  components: {
    CrmRelative
  },
  mixins: [objMixin],
  props: {
    optionsList: Object,
  },
  data() {
    return {
      showPopover: false, // 展示产品框
      showSelectView: false, // 内容
      productList: [],
      quotationData: {},
      selectedData: { product: [] },
      // 增值税率是否低于13
      // reviewRate: 2,
      // 存在价格低于总监价
      reviewPrice: 2,
    }
  },
  computed: {},
  watch: {
    dataValue: function(value) {
      this.refreshProductList()
    },
    productList: {
      handler(val){
        this.selectedData = { product: val || [] }
        // 产品表格数据变化时，跟着触发该方法
        this.changeProductData()
      },
      deep: true,
      immediate: true
    },
  },
  mounted() {
    this.refreshProductList()
  },
  methods: {
    /**
     * 刷新数据
     */
    refreshProductList() {
      this.quotationData = this.dataValue;
      this.quotationData.salesTotalPrice = this.dataValue.salesTotalPrice || 0;
      this.quotationData.settlementTotalPrice = this.dataValue.settlementTotalPrice || 0;
      this.quotationData.directorTotalPrice = this.dataValue.directorTotalPrice || 0;
      this.productList = this.quotationData.productList || []
    },

    /** 选中 */
    selectInfos(data) {
      if (data.data) {
        const newSelects = []
        data.data.forEach(element => {
          const obj = this.productList.find(item => {
            return item.productId == element.productId
          })
          if (obj) {
            newSelects.push(obj)
          } else {
            newSelects.push(this.getShowItem(element))
          }
        })
        this.productList = newSelects
      }
    },

    // 每一项产品数据替换
    getShowItem(data) {
      const item = {}
      item.productName = data.name
      item.productModel = data.specName
      item.balance = data.balance
      item.productPrice = Number(data.salesPriceTax) //销售单价
      item.directorPrice = Number(data.directorPriceTax) //总监单价
      item.settlementPrice = Number(data.settlementPriceTax) //结算单价
      item.productNumber = 1
      item.totalPrice = numberMul(item.productNumber,item.productPrice);
      item.settlementTotalPrice = numberMul(item.productNumber,item.directorPrice);
      item.directorTotalPrice = numberMul(item.productNumber,item.settlementPrice);
      item.productId = data.productId;
      return item
    },

    //更改增值税率
    // changeRate(val){
    //   this.reviewRate = 2;
    //   if(val < 13){
    //     // 更改增值税率时，如果低于13，则将该值置为true
    //     this.reviewRate = 1;
    //     // 触发数据更新
    //   }
    //   this.updateValue();
    // },

    // 产品部分数据更改触发该方法
    changeData(rowData,type){
      let errMsg = "";
      if(type == 'productPrice'){
        if(Number(rowData.row[type]) < 0){
          rowData.row[type] = 0
          errMsg += "产品 ‘" + rowData.row.name + "’ 的单价不能小于0";
        }
      }else if(type == 'productNumber'){
        if(Number(rowData.row[type]) < 1){
          rowData.row[type] = 1
          errMsg += "产品 ‘" + rowData.row.name + "’ 的数量不能小于1";
        }
      }
      if(errMsg.length){
        this.$message.error(errMsg);
      }
    },

    //每个产品自动计算总价
    // calculationTotalPrice(rowData){
    //   rowData.row.salesTotalPrice = rowData.row.productNumber * rowData.row.productPrice;
    //   rowData.row.settlementTotalPrice = rowData.row.productNumber * rowData.row.settlementPrice;
    //   rowData.row.directorTotalPrice = rowData.row.productNumber * rowData.row.directorPrice;
    //   return rowData.row.salesTotalPrice
    // },

    //更改数据后触发该方法
    changeProductData(){
      let item = this.quotationData;
      item.subtotal = 0; //小计
      item.settlementTotalPrice = 0;
      item.directorTotalPrice = 0;
      this.reviewPrice = 2;
      
      let list = this.productList;
      list.map(product => {
        product.totalPrice = numberMul(product.productNumber,product.productPrice);
        product.settlementTotalPrice = numberMul(product.productNumber,product.directorPrice);
        product.directorTotalPrice = numberMul(product.productNumber,product.settlementPrice);
        item.subtotal = numberAdd(item.subtotal,product.totalPrice);
        item.settlementTotalPrice = numberAdd(item.settlementTotalPrice,product.settlementTotalPrice);
        item.directorTotalPrice = numberAdd(item.directorTotalPrice,product.directorTotalPrice);
        // 如果产品存在一项销售单价大于 总监单价，则置为true
        if(product.productPrice < product.directorPrice){
          this.reviewPrice = 1;
        }
      })
      this.quotationData.productList = list;
      this.updateValue();
      // this.changeRate(this.quotationData.rate);
    },

    

    // 删除操作
    removeItem(index) {
      this.productList.splice(index, 1)
    },
    
    // 数据更新
    updateValue() {
      // this.quotationData.reviewRate = this.reviewRate;
      this.quotationData.reviewPrice = this.reviewPrice;
      this.valueChange({
        quotationData: this.quotationData,
      })
    },
    /**
     * 验证数据数值是否符合
     */
    verifyNumberValue(data, field) {
      if (/^\d+\.?\d{0,2}$/.test(data.row[field])) {
        data.row[field] = data.row[field]
      } else {
        data.row[field] = data.row[field].substring(
          0,
          data.row[field].length - 1
        )
      }
    },
  }
}
</script>
<style lang="scss" scoped>
.handel-header {
  border-top: 1px solid #ddd;
  padding-top: 10px;
  button {
    float: right;
    margin-bottom: 10px;
  }
}

.el-table /deep/ thead th {
  font-size: 12px;
}

.el-table /deep/ tbody tr td {
  font-size: 12px;
}

.handle-footer {
  font-size: 12px;
  padding: 5px;
  .discount-title {
    color: #666;
  }
  .total-info {
    .info-yellow {
      color: #fd715a;
    }
  }
}
</style>
